package com.kmxd.ams.controller.system.index;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kmxd.ams.client.archive.IArchiveTypeSvc;
import com.kmxd.ams.client.system.ISysFondsSvc;
import com.kmxd.ams.client.system.ISysJobsSvc;
import com.kmxd.ams.client.system.ISysMessagesSvc;
import com.kmxd.ams.client.system.ISysNoticeSvc;
import com.kmxd.ams.client.system.dto.SysMessagesQueryDTO;
import com.kmxd.ams.client.system.dto.SysNoticeQueryDTO;
import com.kmxd.ams.client.system.dto.SysNoticeTypeQueryDTO;
import com.kmxd.ams.client.system.vo.SysMessagesListVO;
import com.kmxd.ams.client.system.vo.SysNoticeListVO;
import com.kmxd.ams.client.system.vo.SysNoticeTypeListVO;
import com.kmxd.ams.core.common.enums.MessageStatusEnum;
import com.kmxd.ams.core.common.enums.MessageTypeEnum;
import com.kmxd.ams.core.common.enums.NoticeSendStatusEnum;
import com.kmxd.ams.core.result.R;
import com.kmxd.ams.core.util.SecurityUtil;
import com.kmxd.ams.infra.archive.entity.ArchiveType;
import com.kmxd.ams.infra.system.entity.SysFonds;
import com.kmxd.ams.infra.system.entity.SysJobs;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 首页 前端控制器
 *
 * @author admin
 */
@Tag(name = "系统首页")
@RestController
@RequestMapping("/SysIndex")
@AllArgsConstructor
public class SysIndexCtl {

  private ISysNoticeSvc sysNoticeSvc;
  private ISysMessagesSvc sysMessagesSvc;
  private ISysFondsSvc sysFondsSvc;
  private IArchiveTypeSvc archiveTypeSvc;
  private ISysJobsSvc sysJobsSvc;

  @GetMapping("/index")
  public R<Void> index(HttpServletResponse response) {
    return R.success();
  }

  /** 获取我的通知信息 */
  @Operation(summary = "获取我的通知信息类型")
  @GetMapping("/getMyNoticeType")
  public R<List<SysNoticeTypeListVO>> getMyNoticeType(SysNoticeTypeQueryDTO req) {
    req.setComId(SecurityUtil.getCropId());
    return R.success(sysNoticeSvc.selectUserNoticeType(req));
  }

  /** 获取我的通知信息 */
  @Operation(summary = "获取我的通知信息")
  @GetMapping("/getMyNotice")
  public R<Page<SysNoticeListVO>> getMyNotice(Page reqPage, SysNoticeQueryDTO req) {
    req.setSendTime(new Date());
    req.setStatus(NoticeSendStatusEnum.PUBLISHED.getType());
    req.setComId(SecurityUtil.getCropId());
    return R.success(sysNoticeSvc.selectUserPage(reqPage, req));
  }

  /** 获取我的待办消息 */
  @Operation(summary = "获取我的待办消息")
  @GetMapping("/getMyTodoList")
  public R<Page<SysMessagesListVO>> getMyTodoList(Page reqPage, SysMessagesQueryDTO req) {
    req.setStatus(MessageStatusEnum.UNREAD.getType());
    req.setComId(SecurityUtil.getCropId());
    req.setMsgCategory(MessageTypeEnum.AGENCY.getType());
    req.setRoleId(SecurityUtil.getLoginUser().getRoleId());
    req.setDeptId(SecurityUtil.getLoginUser().getDeptId());
    req.setUserId(SecurityUtil.getUserId());
    return R.success(sysMessagesSvc.selectUserPage(reqPage, req));
  }

  /** 获取我的待办消息 */
  @Operation(summary = "获取我的消息")
  @GetMapping("/getMyMessages")
  public R<Page<SysMessagesListVO>> getMyMessages(Page reqPage, SysMessagesQueryDTO req) {
    req.setStatus(MessageStatusEnum.UNREAD.getType());
    req.setComId(SecurityUtil.getCropId());
    req.setMsgCategory(MessageTypeEnum.NOTICE.getType());
    req.setRoleId(SecurityUtil.getLoginUser().getRoleId());
    req.setDeptId(SecurityUtil.getLoginUser().getDeptId());
    req.setUserId(SecurityUtil.getUserId());
    return R.success(sysMessagesSvc.selectUserPage(reqPage, req));
  }

  /** 统计全宗及档案库数量 */
  @Operation(summary = "统计全宗及档案库数量")
  @GetMapping("/statisticalArch")
  public R statisticalArch() {
    long fondsTotal =
        sysFondsSvc.count(
            Wrappers.lambdaQuery(SysFonds.class).eq(SysFonds::getComId, SecurityUtil.getCropId()));
    LambdaQueryWrapper<ArchiveType> queryWrapper = Wrappers.lambdaQuery();
    queryWrapper.eq(ArchiveType::getComId, SecurityUtil.getCropId());
    long archTotal = archiveTypeSvc.count(queryWrapper);
    Map<String, Object> map = MapUtil.newHashMap();
    map.put("fondsTotal", fondsTotal);
    map.put("archTotal", archTotal);
    return R.success(map);
  }

  /** 查询监控信息 */
  @Operation(summary = "查询监控信息")
  @GetMapping("/monitorInfo")
  public R<List<SysJobs>> monitorInfo() {
    return R.success(sysJobsSvc.monitorInfo());
  }

  @Operation(summary = "文件打印预览中转")
  @GetMapping(value = "/relay")
  @SneakyThrows
  public void fileRelay(@RequestParam String param, HttpServletResponse response) {
    if (StrUtil.isBlank(param)) {
      // url为空时不处理
      return;
    }
    Environment env = SpringUtil.getApplicationContext().getEnvironment();
    String port = env.getProperty("server.port");
    String path = env.getProperty("server.servlet.context-path");
    String url = "http://localhost:" + port + path + "/ureport/preview" + param;
    byte[] buffer = HttpUtil.downloadBytes(url);
    if (ObjectUtil.isNotEmpty(buffer)) {
      String filename = "_预览打印_" + System.currentTimeMillis() + ".pdf";
      response.setContentType("application/pdf");
      response.setCharacterEncoding("UTF-8");
      response.setHeader(
          "Content-Disposition",
          "attachment;filename=" + URLUtil.encode(filename, StandardCharsets.UTF_8));
      IoUtil.write(response.getOutputStream(), true, buffer);
    }
  }
}
